/*
			            FileReader共有4种读取方法：
			            1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
			            2.readAsBinaryString(file)：将文件读取为二进制字符串
			            3.readAsDataURL(file)：将文件读取为Data URL
			            4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
			                         */
var wb; //读取完成的数据
var rABS = false; //是否将文件读取为二进制字符串
var sheetIndex = 0;// 默认展示下标
var grid;

var colIndex = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

//导入
function importf(obj) {
    if (!obj.files) {
        return;
    }
    var f = obj.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        var data = e.target.result;
        if (rABS) {
            wb = XLSX.read(btoa(fixdata(data)), { //手动转化
                type: 'base64'
            });
        } else {
            wb = XLSX.read(data, {
                type: 'binary'
            });
        }
        //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        //wb.Sheets[Sheet名]获取第一个Sheet的数据
        //document.getElementById("demo").innerHTML= JSON.stringify( XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) );
        console.log(wb.SheetNames);
        load(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[sheetIndex]]));
    };
    if (rABS) {
        reader.readAsArrayBuffer(f);
    } else {
        reader.readAsBinaryString(f);
    }
}

//文件流转BinaryString
function fixdata(data) {
    var o = "",
        l = 0,
        w = 10240;
    for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
    return o;
}

function load(data) {
    console.log(data);
    var parentNode = document.getElementById('grid');
    // create a new grid
    grid = canvasDatagrid({
        parentNode: parentNode,
        data: data
    });



    grid.addEventListener('click', function (e) {
        if (!e.cell) {
            return;
        }
        grid.data[0][grid.schema[0].name] = 'Just arrived at '
            + e.cell.columnIndex + ', ' + e.cell.rowIndex;
        console.log(e.cell.value);

    });

    grid.addEventListener('blur', function (e) {
        console.log('blur:' + e.cell.value);
    });

    // grid.addEventListener('cellmouseover', function (e) {
    //     if (!e.cell) { return; }
    //     grid.data[0][grid.schema[0].name] = 'Just arrived at '
    //         + e.cell.columnIndex + ', ' + e.cell.rowIndex;
    //
    // });
    // grid.addEventListener('cellmouseout', function (e) {
    //     if (!e.cell) { return; }
    //     grid.data[1][grid.schema[0].name] = 'Just came from '
    //         + e.cell.columnIndex + ', ' + e.cell.rowIndex;
    // });

    // grid.style.columnHeaderCellBackgroundColor = 'dodgerblue';
    // grid.style.columnHeaderCellColor = 'white';
    // gradient = grid.ctx.createLinearGradient(0, 0, 1300, 1300);
    // gradient.addColorStop(0, 'dodgerblue');
    // gradient.addColorStop(1, 'chartreuse');
    // grid.style.cellBackgroundColor = gradient;
    // grid.style.gridBackgroundColor = gradient;


    // grid.addEventListener('rendercell', function (e) {
    //     if (e.cell.header.name === 'Ei' && /omittam/.test(e.cell.value)) {
    //         e.ctx.fillStyle = '#AEEDCF';
    //     }
    // });

    // grid.addEventListener('beforeendedit', function (e) {
    //     // if (/\d+/.test(e.newValue)) {
    //     //     alert('NO DIGITS!');
    //     //     e.preventDefault();
    //     // }
    //     console.log("a:"+e.cell.value);
    // });
    //
    // grid.addEventListener('afterrendercell', function (e) {
    //     // if (/\d+/.test(e.newValue)) {
    //     //     alert('NO DIGITS!');
    //     //     e.preventDefault();
    //     // }
    //     console.log("b:"+e.cell.value);
    // });

    //
    // grid.addEventListener('rendertext', function (e) {
    //     // if (e.cell.rowIndex > -1) {
    //     //     if (e.cell.header.name === 'MyImageColumnName') {
    //     //         e.cell.formattedValue = e.cell.value ? '' : 'No Image';
    //     //     }
    //     // }
    //     console.log("C:"+e.cell.value);
    // });

    grid.addEventListener('beforeendedit', function (e) {
        // if (/\d+/.test(e.newValue)) {
        //     console.log('NO DIGITS!'+e.newValue);
        //     e.preventDefault();
        // }
        console.log('NO DIGITS!'+e.newValue);
        e.preventDefault();
    });

    //  允许在网格底部输入新行。
    grid.attributes.showNewRow = true;


    grid.addEventListener('rendercell', function (e) {
        console.log(e.cell.header.name);
        if (e.cell.header.name === 'MyStatusCell' && /blah/.test(e.cell.value)) {
            e.ctx.fillStyle = '#AEEDCF';
        }
    });
}

function writeFile() {
    XLSX.writeFile(wb, "SheetJS.xlsx", {
        compression: true
    });

}


function openFile() {
    var url = "http://localhost:8080/test.xlsx";

    /* set up async GET request */
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.responseType = "arraybuffer";

    req.onload = function (e) {
        var data = new Uint8Array(req.response);
        var workbook = XLSX.read(data, {type: "array"});

        wb = workbook;

        console.log(wb.Sheets[wb.SheetNames[sheetIndex]]);

        document.querySelector("#grid-html").innerHTML = XLSX.utils.sheet_to_html(wb.Sheets[wb.SheetNames[sheetIndex]]);

        load(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[sheetIndex]]));

    }

    req.send();
}

function addRow() {
    grid.addRow({
        col1: 'a ' + new Date().toString(),
        col2: 'a ' + new Date().toString(),
        col3: 'a ' + new Date().toString()
    });
}
